
package com.tenglong.teacher.ui.login;


import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Process;
import android.support.annotation.NonNull;
import android.text.InputType;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;

import com.cuotibao.zhuoxiao.basics.GlobalConstant;
import com.cuotibao.zhuoxiao.basics.utils.ClassPathResource;
import com.cuotibao.zhuoxiao.basics.utils.ToastUtils;
import com.cuotibao.zhuoxiao.basics.utils.Utils;
import com.tenglong.teacher.R;
import com.tenglong.teacher.ui.common.activity.BaseActivity;
import com.tenglong.teacher.ui.common.view.XEditText;
import com.tenglong.teacher.ui.downApk.IContract;
import com.tenglong.teacher.ui.downApk.iView.ViewPresenter;
import com.tenglong.teacher.ui.register.ForgetPasswordActivity;
import com.tenglong.teacher.ui.register.RegisterActivity;
import com.tenglong.teacher.ui.setting.FragmentSetting;
import com.tenglong.teacher.ui.utils.StringUtils;


public class LoginActivity extends BaseActivity implements OnClickListener, IContract.CheckUpdateListener, XEditText.DrawableRightListener {

    /**
     * 登录账号输入控件
     */
    private EditText loginNameEdit;
    /**
     * 登录密码输入控件
     */
    private XEditText passwordEdit;
    /**
     * 登录业务对象
     */
    private LoginUtil loginUtil;

    private ViewPresenter mPresenter;

    private boolean isCheckSucceed = false;

    private boolean isHasNewsVerion = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Utils.isGrantExternalRW(this)) {
            initView();
        }
    }

    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == GlobalConstant.REQUEST_CODE_LOGIN_ACTIVITY) {
            if (permissions.length != grantResults.length) {
                finish();
                Process.killProcess(Process.myPid());
                return;
            }
            for (int i = 0; i < permissions.length; i++) {
                String permission = permissions[i];
                int grantResult = grantResults[i];
                if (grantResult != PackageManager.PERMISSION_GRANTED) {
                    finish();
                    Process.killProcess(Process.myPid());
                    return;
                }
            }
            initView();
        }
    }

    private void initView() {
        setContentView(R.layout.activity_login);
        setTitle("登录");
        findViewById(R.id.btn_login).setOnClickListener(this);
        findViewById(R.id.register).setOnClickListener(this);
        findViewById(R.id.forgetPassword).setOnClickListener(this);
        loginNameEdit = findViewById(R.id.et_phone);
        loginNameEdit.setInputType(InputType.TYPE_CLASS_PHONE);
        passwordEdit = findViewById(R.id.et_pwd);
        passwordEdit.setDrawableRightListener(this);
        mBack.setVisibility(View.GONE);
        SharedPreferences settings = getSharedPreferences("preference", 0);
        loginNameEdit.setText(settings.getString(StringUtils.PHONE_KEY, ""));
        passwordEdit.setText(settings.getString(StringUtils.PASSWORD_KEY, ""));
        loginNameEdit.setSelection(loginNameEdit.getText().toString().length());
        passwordEdit.setSelection(passwordEdit.getText().toString().length());
        showProgressDialog("版本检测中...");
        updateApk();
    }

    private void auLogin() {
        if (!ClassPathResource.isStringEmpty(loginNameEdit.getText().toString()) && !ClassPathResource.isStringEmpty(passwordEdit.getText().toString())) {
            SharedPreferences settings = getSharedPreferences("preference", 0);
            if (settings.getBoolean(StringUtils.USER_LOGIN_STATE,false)){
                onClick(findViewById(R.id.btn_login));
            }
        }
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.btn_login:
                if (ClassPathResource.isStringEmpty(loginNameEdit.getText().toString())
                        || ClassPathResource.isStringEmpty(passwordEdit.getText().toString())) {
                    ToastUtils.showCenterToast("账号或密码不能为空");
                    return;
                } else if (!ClassPathResource.isMobileNO(loginNameEdit.getText().toString())) {
                    ToastUtils.showCenterToast("账号只能为电话号码");
                    return;
                } else if (!isCheckSucceed) {
                    ToastUtils.showCenterToast("数据检测中,请稍后...");
                    return;
                } else if (isHasNewsVerion) {
                    ToastUtils.showCenterToast("请去下载最新版本");
                    return;
                }
                if (loginUtil == null) {
                    loginUtil = new LoginUtil(this, new LoginUtil.LoginCallback() {
                        @Override
                        public void showLoadingDialog() {
                            showProgressDialog(getString(R.string.login_logining_tip));
                        }

                        @Override
                        public void dissLoadingDialog() {
                            dismissProgressDialog();
                        }

                        @Override
                        public void showToast(String message) {
                            ToastUtils.showCenterToast(message);
                        }
                    });
                }
                loginUtil.login(loginNameEdit.getText().toString().trim(), passwordEdit.getText().toString().trim());
                break;
            case R.id.register:
                startActivityForResult(new Intent(this, RegisterActivity.class), GlobalConstant.REQUEST_CODE_REGISTER_ACTIVITY);
                break;
            case R.id.forgetPassword:
                startActivity(new Intent(this, ForgetPasswordActivity.class));
                break;
        }
    }


    private void updateApk() {
        mPresenter = new ViewPresenter(this);
        try {
            mPresenter.checkUpdate(getPackageManager().getPackageInfo(getPackageName(), 0).versionCode, this);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case GlobalConstant.REQUEST_CODE_REGISTER_ACTIVITY:
                    if (data != null) {
                        String phone = data.getStringExtra(GlobalConstant.RESULT_CODE_REGISTER_PHONE);
                        String password = data.getStringExtra(GlobalConstant.RESULT_CODE_REGISTER_PASSWORD);
                        loginNameEdit.setText(phone == null ? "" : phone);
                        passwordEdit.setText(password == null ? "" : password);
                        loginNameEdit.setSelection((phone == null ? "" : phone).length());
                        passwordEdit.setSelection((password == null ? "" : password).length());
                    }
                    break;
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mPresenter.onDestroy();//解除绑定
    }

    @Override
    public void onIsHasNewsVersion(boolean isHasNewsVersion) {
        this.isHasNewsVerion = isHasNewsVersion;
        this.isCheckSucceed = true;
        dismissProgressDialog();
        if (isHasNewsVersion) {
            return;
        }
        Intent i = getIntent();
        String exitInfo = i.getStringExtra(FragmentSetting.KEY_APP_EXIT);
        if (exitInfo == null) {
            auLogin();
        }
    }

    @Override
    public void onDrawableRightClick(View view) {
        EditText editText = (EditText) view;
        int length = editText.getText().toString().length();
        if (TextUtils.isEmpty(editText.getText().toString())) {
            if (!editText.isSelected()) {
                ToastUtils.showCenterToast("请先输入密码");
                return;
            }
        }
        editText.setSelected(!editText.isSelected());
        if (editText.isSelected()) {
            //如果选中，显示密码
            editText.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
        } else {
            //否则隐藏密码
            editText.setTransformationMethod(PasswordTransformationMethod.getInstance());
        }
        editText.setSelection(length);
    }
}
